//package com.amigo.online.provider.search.service.impl;
//
//import java.util.ArrayList;
//import java.util.HashMap;
//import java.util.List;
//import java.util.Map;
//import java.util.concurrent.ArrayBlockingQueue;
//import java.util.stream.Collectors;
//
//import javax.annotation.Resource;
//
//import org.apache.solr.client.solrj.SolrClient;
//import org.apache.solr.client.solrj.SolrQuery;
//import org.apache.solr.client.solrj.response.QueryResponse;
//import org.apache.solr.client.solrj.response.TermsResponse;
//import org.apache.solr.common.SolrDocument;
//import org.apache.solr.common.SolrDocumentList;
//import org.slf4j.Logger;
//import org.slf4j.LoggerFactory;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.data.redis.core.ListOperations;
//import org.springframework.http.ResponseEntity;
//import org.springframework.stereotype.Service;
//
//import com.amigo.online.common.base.security.LocalUser;
//import com.amigo.online.common.core.response.Response;
//import com.amigo.online.common.core.response.StatusCode;
//import com.amigo.online.common.param.dto.query.Searchparam;
//import com.amigo.online.common.param.result.MusicInfo;
//import com.amigo.online.common.param.result.VideoInfo;
//import com.amigo.online.common.param.result.VideoInfo.VideoUserInfo;
//import com.amigo.online.common.util.StringUtils;
//import com.amigo.online.provider.search.exception.Consumer;
//import com.amigo.online.provider.search.exception.SearchException;
//import com.amigo.online.provider.search.model.SearchResponseResult;
//import com.amigo.online.provider.search.service.MusicFeignService;
//import com.amigo.online.provider.search.service.SearchService;
//import com.amigo.online.provider.search.service.UserFeignService;
//import com.amigo.online.provider.search.service.VideoFeignService;
//import com.fasterxml.jackson.core.type.TypeReference;
//import com.fasterxml.jackson.databind.ObjectMapper;
//
//@Service
//public class SearchServiceImpl implements SearchService {
//	
//	private static final Logger log = LoggerFactory.getLogger(SearchServiceImpl.class);
//	
//	@Resource(name = "SolrClient_user")
//	private SolrClient solrClient_user;
//	
//	@Resource(name = "SolrClient_video")
//	private SolrClient solrClient_video;
//	
//	@Resource(name = "SolrClient_music")
//	private SolrClient solrClient_music;
//	
//	@Resource(name = "SolrClient_hotword")
//	private SolrClient solrClient_hotword;
//	
//	@Autowired
//	private Consumer consumer;
//	
//	@Autowired
//	private VideoFeignService videoFeignService;
//	
//	@Autowired
//	private UserFeignService userFeignService;
//	
//    @Autowired
//    MusicFeignService musicFeignService;
//    
//	@Resource
//	private ListOperations<String, Object> listOperations;
//	
//	private static final int queueSize = 5;
//	
//	public static final ArrayBlockingQueue<String> queue = new ArrayBlockingQueue<String>(queueSize);
//	
//	//private static final int produceSpeed = 2000;// 生产速度(越小越快)
//	
//	//private static final int consumeSpeed = 10;// 消费速度(越小越快)
//	
//	private static final String NULL_STRING = "null";
//	
//	public static String escapeQueryChars(String s) {
//	    StringBuilder sb = new StringBuilder();
//	    for (int i = 0; i < s.length(); i++) {
//	      char c = s.charAt(i);
//	      // These characters are part of the query syntax and must be escaped
//	      if (c == '\\' || c == '+' || c == '-' || c == '!'  || c == '(' || c == ')' || c == ':'
//	        || c == '^' || c == '[' || c == ']' || c == '\"' || c == '{' || c == '}' || c == '~'
//	        || c == '*' || c == '?' || c == '|' || c == '&'  || c == ';' || c == '/'
//	        || Character.isWhitespace(c)) {
//	        sb.append('\\');
//	      }
//	      sb.append(c);
//	    }
//	    return sb.toString();
//	  }
//	
//	@Override
//	public Map<String, Object> search(Searchparam searchparam) throws Exception {
//		if (searchparam == null) {
//			throw new SearchException(StatusCode.BAD_REQUEST);
//		}
//		String temq = searchparam.getQ();
//		queue.put(temq);
//		consumer.insertHotWord();
//		String q = temq.toLowerCase();
//		q = escapeQueryChars(q);
//		System.out.println(">>>>>>转换后" + q);
//		String rows = searchparam.getRows();
//		String start = searchparam.getStart();
//		if (q == null || StringUtils.isEmpty(q)) {
//			throw new SearchException(StatusCode.BAD_REQUEST);
//		}
//		if (start == null || StringUtils.isEmpty(start)) {
//			throw new SearchException(StatusCode.BAD_REQUEST);
//		}
//		if (rows == null || StringUtils.isEmpty(rows)) {
//			throw new SearchException(StatusCode.BAD_REQUEST);
//		}
//		// 1、创建一个SolrQuery对象。
//		SolrQuery query = new SolrQuery();
//		SolrQuery userQuery = new SolrQuery();
//		// 2、设置查询条件
//		userQuery.setQuery("nickname:*" + q + "* or nickname: \"" + q + "\" or account:" + q + " or mobilephone:" + q);
//		userQuery.set("start", start); // 记录开始位置
//		userQuery.set("rows", rows); // 查询的行数
//		query.setQuery("*" + q + "*");
//		// query.setQuery(q);
//		query.set("start", start); // 记录开始位置
//		query.set("rows", rows); // 查询的行数
//		// 引用solr服务查询
//		QueryResponse videoResponse = null;
//		QueryResponse userResponse = null;
//		userResponse = solrClient_user.query(userQuery);// user
//		videoResponse = solrClient_video.query(query);// video
//		SolrDocumentList list = videoResponse.getResults();
//		if (list.getNumFound() == 0) {
//			query.setQuery(q);
//			videoResponse = solrClient_video.query(query);// video
//		}
//		// 查数据库判断时候关注和点赞
//		// 1.根据videoid查询点赞表
//		List<Long> ids = new ArrayList<Long>();
//		List<Long> userids = new ArrayList<Long>();
//		Map<String, SolrDocument> map = new HashMap<String, SolrDocument>();
//		for (SolrDocument sdc : videoResponse.getResults()) {
//			ids.add(Long.parseLong(sdc.get("id") + ""));
//			userids.add(Long.parseLong(sdc.get("userId") + ""));
//			sdc.addField("uped", false);
//			sdc.addField("followed", false);
//			map.put(sdc.get("id") + "", sdc);
//		}
//		try {
//			log.info("进入video代码段开始：");
//
//			if(LocalUser.getUser()!=null && userids.size() > 0){
//				//是否关注
//				Long userId=LocalUser.getUser().getUser().getId();
//				ResponseEntity<Response>  userVideoIds=userFeignService.getfollowedByUserId(userId,userids);
//				List<?> obj1 = (List<?>) userVideoIds.getBody().getData();
//				// 转map
//				Map<String, Object> videoUserIdMap = new HashMap<String, Object>();
//				if (obj1 != null && obj1.size() > 0) {
//					for (Object obj : obj1) {
//						videoUserIdMap.put(obj.toString(), obj);
//					}
//
//					for (SolrDocument sdc : videoResponse.getResults()) {
//						String userID = sdc.get("userId") + "";
//						if (videoUserIdMap.containsKey(userID)) {
//							sdc.replace("followed", true);
//						}
//					}
//				}
//				// 是否点赞
//				ResponseEntity<Response> videoUpIds = videoFeignService.getUpByVideoId(userId, ids);
//				List<?> obj2 = (List<?>) videoUpIds.getBody().getData();
//				log.info("查询是否点赞为：" + obj1);
//				if (obj2 != null && obj2.size() > 0) {
//					for (Object map1 : obj2) {
//						if (map.get(map1 + "") != null) {
//							map.get(map1 + "").replace("uped", true);
//							log.info("uped为true");
//						}
//					}
//				}
//			}
//		} catch (Exception e) {
//			e.printStackTrace();
//		}
//
//		List<Long> useridss = new ArrayList<Long>();
//		Map<String, SolrDocument> usermap = new HashMap<String, SolrDocument>();
//		for (SolrDocument sdoc : userResponse.getResults()) {
//			useridss.add(Long.parseLong(sdoc.get("id") + ""));
//			sdoc.addField("followed", false);
//			usermap.put(sdoc.get("id") + "", sdoc);
//		}
//		try {
//			log.info("进入user代码段开始：", "进入user代码段开始啦");
//			if (LocalUser.getUser() != null) {
//				Long userId = LocalUser.getUser().getUser().getId();
//				log.info("进入user代码段，userid为：" + userId);
//				ResponseEntity<Response> userIds = userFeignService.getfollowedByUserId(userId, useridss);
//				log.info("查询关注人的id，userIds为：" + userIds);
//				List<?> obj1 = (List<?>) userIds.getBody().getData();
//				log.info("查询关注人的id，userIds为：" + obj1);
//				if (obj1 != null) {
//					for (Object map1 : obj1) {
//						if (usermap.get(map1 + "") != null) {
//							usermap.get(map1 + "").replace("followed", true);
//							log.info("followed为true", true);
//						}
//					}
//				}
//			}
//		} catch (Exception e) {
//			e.printStackTrace();
//		}
//		List<Long> musicIds = new ArrayList<>();
//		// 对video数据重新封装
//		List<VideoInfo> videoList = new ArrayList<VideoInfo>();
//		for (SolrDocument sdcc : videoResponse.getResults()) {
//			//拿到musicIds去数据库中查询music信息
//			if (sdcc.get("id_music") != null && !sdcc.get("id_music").equals("null")) {
//				musicIds.add(Long.parseLong(sdcc.get("id_music") + ""));
//			}
//			VideoInfo video = new VideoInfo();
//			video.setId(Long.parseLong(sdcc.get("id") + ""));
//			video.setDistance(0.00);
//			video.setUserId(Long.parseLong(sdcc.get("userId") == null ? "" : sdcc.get("userId") + ""));
//			video.setVideo(sdcc.get("video") == null ? "" : sdcc.get("video") + "");
//			video.setCover(sdcc.get("cover") == null ? "" : sdcc.get("cover") + "");
//			if (sdcc.get("height") != null && !sdcc.get("height").equals("null")) {
//				video.setHeight(Integer.parseInt(sdcc.get("height") + ""));
//			}
//			if (sdcc.get("width") != null && !sdcc.get("width").equals("null")) {
//				video.setWidth(Integer.parseInt(sdcc.get("width") + ""));
//			}
//			if (sdcc.get("duration") != null && !sdcc.get("duration").equals("null")) {
//				video.setDuration(Integer.parseInt(sdcc.get("duration") + ""));
//			}
//			video.setHref(sdcc.get("href") == null ? "" : sdcc.get("href") + "");
//			if (sdcc.get("type") != null && !sdcc.get("type").equals("null")) {
//				video.setType(Integer.parseInt(sdcc.get("type") + ""));
//			}
//			if (sdcc.get("ads") != null && !sdcc.get("ads").equals("null")) {
//				video.setAds(Integer.parseInt(sdcc.get("ads") + ""));
//			}
//			if (sdcc.get("recommended") != null && !sdcc.get("recommended").equals("null")) {
//				video.setRecommended(Integer.parseInt(sdcc.get("recommended") + ""));
//			}
//			if (sdcc.get("up") != null && !sdcc.get("up").equals("null")) {
//				video.setUp(Integer.parseInt(sdcc.get("up") + ""));
//			}
//			if (sdcc.get("look") != null && !sdcc.get("look").equals("null")) {
//				video.setLook(Integer.parseInt(sdcc.get("look") + ""));
//			}
//			if (sdcc.get("comment") != null && !sdcc.get("comment").equals("null")) {
//				video.setComment(Integer.parseInt(sdcc.get("comment") + ""));
//			}
//			if (sdcc.get("share") != null && !sdcc.get("share").equals("null")) {
//				video.setShare(Integer.parseInt(sdcc.get("share") + ""));
//			}
//			if (sdcc.get("contentcount") != null && !NULL_STRING.equals(sdcc.get("contentcount")))
//				video.setContent(sdcc.get("contentcount").toString());
//			
//			VideoUserInfo videoUserInfo = new VideoUserInfo();
//			videoUserInfo.setAvatar(sdcc.get("avatar") == null ? "" : sdcc.get("avatar") + "");
//			if (sdcc.get("followed") != null && !sdcc.get("followed").equals("null")) {
//				videoUserInfo.setFollowed(Boolean.parseBoolean(sdcc.get("followed") + ""));
//			}
//			videoUserInfo.setLatitude("0");
//			videoUserInfo.setLongitude("0");
//			videoUserInfo.setNickname(sdcc.get("nickname_user") == null ? "" : sdcc.get("nickname_user") + "");
//			if (sdcc.get("uped") != null && !sdcc.get("uped").equals("null")) {
//				videoUserInfo.setUped(Boolean.parseBoolean(sdcc.get("uped") + ""));
//			}
//			
//			/*下面这段构建music方法不用了*/
////			MusicInfo musicInfo = new MusicInfo();
////			if (sdcc.get("id_music") != null && !sdcc.get("id_music").equals("null")) {
////				musicInfo.setId(Long.parseLong(sdcc.get("id_music") == null ? "" : sdcc.get("id_music") + ""));
////			}
////			if (sdcc.get("userId_music") != null && !sdcc.get("userId_music").equals("null")) {
////				musicInfo.setUserId(Long.parseLong(sdcc.get("userId_music") + ""));
////			}
////			if (sdcc.get("name_music") != null && !sdcc.get("name_music").equals("null")) {
////				musicInfo.setName(sdcc.get("name_music") == null ? "" : sdcc.get("name_music") + "");
////			}
////			musicInfo.setMusic(sdcc.get("music_music") == null ? "" : sdcc.get("music_music") + "");
////			if (sdcc.get("category_music") != null && !sdcc.get("category_music").equals("null")) {
////				musicInfo.setCategory(Integer.parseInt(sdcc.get("category_music") + ""));
////			}
////			musicInfo.setCover(sdcc.get("cover_music") == null ? "" : sdcc.get("cover_music") + "");
////			if (sdcc.get("recommended_music") != null && !sdcc.get("recommended_music").equals("null")) {
////				musicInfo.setRecommended(Integer.parseInt(sdcc.get("recommended_music") + ""));
////			}
////			if (sdcc.get("videoId_music") != null && !sdcc.get("videoId_music").equals("null")) {
////				musicInfo.setVideoId(Long.parseLong(sdcc.get("videoId_music") + ""));
////			}
////			if (sdcc.get("used_music") != null && !sdcc.get("used_music").equals("null")) {
////				musicInfo.setUsed(Integer.parseInt(sdcc.get("used_music") + ""));
////			}
////			if (sdcc.get("type_music") != null && !sdcc.get("type_music").equals("null")) {
////				musicInfo.setType(Integer.parseInt(sdcc.get("type_music") + ""));
////			}
////			if (sdcc.get("createdTime_music") != null && !sdcc.get("createdTime_music").equals("null")) {
////				musicInfo.setCreatedTime(Long.parseLong(sdcc.get("createdTime_music") + ""));
////			}
//			
//		
//			video.setUser(videoUserInfo);
////			video.setMusic(musicInfo);
//			if (sdcc.get("id_music") != null && !sdcc.get("id_music").equals("null")) {
//				video.setMusicId(Long.parseLong(sdcc.get("id_music") + ""));
//			}
//			videoList.add(video);
//		}
//		
//		//构建music信息改从mysql中获取 2018/9/18 by kml
//		ResponseEntity<Response> res = musicFeignService.getMusicByIds(musicIds );
//		Object o = res.getBody().getData();
//		ObjectMapper x = new ObjectMapper();
//		List<MusicInfo> musicInfoList = x.convertValue(o, new TypeReference<List<MusicInfo>>() {});
//		Map<Long,MusicInfo> musicInfoMaps = musicInfoList.stream().collect(Collectors.toMap(MusicInfo::getId, a -> a));
//		for (VideoInfo v : videoList) {
//			v.setMusic(musicInfoMaps.get(v.getMusicId()));
//		}
//		//kml end
//		
//		HashMap<String, Object> hashMap = new HashMap<String, Object>();
//		// 组装数据
//		hashMap.put("user", userResponse.getResults());
//		hashMap.put("video", videoList);
//		// hashMap.put("music",response3.getResults());
//		return hashMap;
//	}
//
//	@Override
//	public SearchResponseResult getHotWord() throws Exception {
//		List<Map<String, Object>> arrayList = new ArrayList<Map<String, Object>>();
//		SearchResponseResult searchResponseResult = new SearchResponseResult();
//		// 创建查询参数以及设定的查询参数
//		SolrQuery query = new SolrQuery();
//		query.set("q", "*:*");
//		query.set("start", 0); // 记录开始位置
//		query.set("rows", 10); // 查询的行数
//		query.set("qt", "/terms");
//		// parameters settings for terms requesthandler
//		// 参考（refer to）http://wiki.apache.org/solr/termscomponent
//		query.set("terms", "true");
//		query.set("terms.fl", "hotword");
//		query.set("terms.regex.flag", "case_insensitive");
//		query.set("terms.sort", "count");// terms.sort={count|index} -如果count，各种各样的条款术语的频率（最高计数第一）。
//											// 如果index，索引顺序返回条款。默认是count
//		// 查询并获取相应的结果！
//		QueryResponse response = solrClient_hotword.query(query);
//		// 获取相关的查询结果
//		if (response != null) {
//			TermsResponse termsResponse = response.getTermsResponse();
//			if (termsResponse != null) {
//				Map<String, List<TermsResponse.Term>> termsMap = termsResponse.getTermMap();
//				for (Map.Entry<String, List<TermsResponse.Term>> termsEntry : termsMap.entrySet()) {
//					List<TermsResponse.Term> termList = termsEntry.getValue();
//					for (TermsResponse.Term term : termList) {
//						HashMap<String, Object> hashMap = new HashMap<String, Object>();
//						hashMap.put("hotWord", term.getTerm());
//						hashMap.put("count", term.getFrequency());
//						arrayList.add(hashMap);
//					}
//				}
//			}
//		}
//		searchResponseResult.setData(arrayList);
//		return searchResponseResult;
//	}
//
//}
